package cn.itrigger.publish;

import cn.itrigger.config.VersionConfig;
import cn.itrigger.utils.CommandLineUtils;
import cn.itrigger.utils.GitOperatorUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;

import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ProdVersionPublish extends ReleaseVersionPublish {

    private VersionConfig config;

    public ProdVersionPublish(VersionConfig config) {
        this.config = config;
    }

    @Override
    public Void publish() throws MojoExecutionException {
        String oldVersion = config.getProject().getVersion();
        String newVersion = null;

        //如果updateVersion是true，则更新版本号
        if (StringUtils.isNotBlank(config.getUpdateVersion()) && Boolean.valueOf(config.getUpdateVersion())) {
            if (StringUtils.isNotBlank(config.getFixVersionNumber())) {
                newVersion = config.getFixVersionNumber();
            }else {
                String[] split = StringUtils.split(oldVersion.replace(config.getUatSubffix(), ""),".");
                switch (config.getVersionLevel()) {
                    case MAX_VERSION:
                        //大版本处理
                        int firstVersionNum = Integer.parseInt(split[0]);
                        newVersion = StringUtils.joinWith(".",firstVersionNum,0,0);
                        break;
                    case MIDDLE_VERSION:
                        //中版本处理
                        int secondVersionNum = Integer.parseInt(split[1]);
                        newVersion = StringUtils.joinWith(".",split[0],secondVersionNum,0);
                        break;
                    case HOTFIX_VERSION:
                        //hotfix版本处理
                        if (split.length == 3) {
                            newVersion = StringUtils.joinWith(".",split[0],split[1],split[2],1);
                        }else {
                            if (oldVersion.endsWith("u")) {
                                newVersion = StringUtils.joinWith(".",split[0],split[1],split[2],split[3]);
                            }else {
                                newVersion = StringUtils.joinWith(".",split[0],split[1],split[2],Integer.parseInt(split[3])+1);
                            }

                        }
                        break;
                    default:
                        //默认普通版本处理，可能会继承自uat环境的hotfix版本
                        if (split.length == 4){
                            newVersion = StringUtils.joinWith(".",split[0],split[1],split[2],split[3]);
                        }else {
                            newVersion = oldVersion.replace(config.getUatSubffix(), "");
                        }

                        break;
                }
            }

            //更新pom.xml文件中的版本号（包括子模块）
            updateVersion(newVersion);
        } else {
            newVersion = oldVersion;
        }

        updateDependencyVersion(config.getUatSubffix(), config.getProdSubffix());

        commitPoms(config);
        GitOperatorUtils.push(" origin " + config.getProdBranch());

        if (StringUtils.isNotBlank(config.getDeploy()) && Boolean.valueOf(config.getDeploy())) {
            deployToNexus(config);
        } else {
            packageToLocal(config);
        }

        String removeBak = "sudo rm -rf pom.xml.versionsBackup";
        System.out.println(removeBak);
        CommandLineUtils.execCmdWithoutResult(removeBak);

        //打标签
        if (BooleanUtils.toBoolean(config.getTag())) {
            GitOperatorUtils.tag(newVersion);
        }
        //切换到daily分支并更新版本号
        if (BooleanUtils.toBoolean(config.getUpdateDailyVersion())) {
            nextSnapshotVersion(newVersion);
        }

        GitOperatorUtils.checkout(config.getProdBranch());
        return null;
    }

    /**
     * 生成下一个snapshot版本
     * @param newVersion
     */
    private void nextSnapshotVersion(String newVersion) {
        //git切换到dailyBranch分支
        System.out.println("dailyBranch==="+config.getDailyBranch());
        GitOperatorUtils.checkout(config.getDailyBranch());
        GitOperatorUtils.pull(config.getDailyBranch());
        GitOperatorUtils.reset();

        String[] split = StringUtils.split(newVersion, ".");
        String version = StringUtils.joinWith(".",split[0],split[1],Integer.parseInt(split[2])+1);
        version = version + config.getDailySubffix();

        if (StringUtils.isNotBlank(config.getUpdateVersion()) && Boolean.valueOf(config.getUpdateVersion())) {
            updateVersion(version);
        }

        commitPoms(config);
        GitOperatorUtils.push(" origin " + config.getDailyBranch());
    }

    private void updateDependencyVersion(String uatSubffix, String prodSubffix) {
        Properties properties = config.getProject().getProperties();
        Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();

        for (Map.Entry<Object, Object> entry : entrySet) {
            if (entry.getValue().toString().endsWith(config.getUatSubffix())) {
                if (entry.getValue().toString().endsWith(uatSubffix)) {
                    String result = CommandLineUtils.execCmdWithResult("mvn versions:set-property -Dproperty=" + entry.getKey().toString() + " -DnewVersion=" + entry.getValue().toString().replace(uatSubffix, prodSubffix));
                    System.out.println(result);
                }
            }
        }
    }

}
